<template>
  <div class="video-container">
    <div class="video-box" v-if="showCamera">
      <video ref="cameraRef" autoplay muted class="video-element"></video>
      <!-- <el-button type="primary" @click="startCamera">摄像头传输</el-button> -->
    </div>

    <div class="video-box" v-if="showScreen">
      <video ref="screenRef" autoplay class="video-element"></video>
      <el-button type="primary" @click="startScreenShare">开启共享</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  showCamera: { type: Boolean, default: false },
  showScreen: { type: Boolean, default: false },
});
const showCamera = ref(props.showCamera);
const showScreen = ref(props.showScreen);

let ws, pc, localStream;
const cameraRef = ref(null);
const screenRef = ref(null);
// const cameraStream = ref(null);
const screenStream = ref(null);
// const cameraPeerConnection = ref(null);
// const screenPeerConnection = ref(null);

// 摄像头处理
const myName = ref("11");
const startCamera = async () => {
  try {
    if (!myName.value.trim()) return alert("请输入名称");
    localStream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 720 },
        height: { ideal: 405 },
        frameRate: { ideal: 30 },
      },
      audio: true,
    });
    cameraRef.value.srcObject = localStream;
    ElMessage.success("摄像头已启动");

    ws = new WebSocket("ws://10.10.0.80:10102/ws?name=" + myName.value.trim());
    ws.onmessage = async (msg) => {
      const data = JSON.parse(msg.data);
      if (data.type === "offer") {
        await createPeerConnection(data.from);
        await pc.setRemoteDescription(new RTCSessionDescription(data.payload));
        const answer = await pc.createAnswer();
        await pc.setLocalDescription(answer);
        ws.send(
          JSON.stringify({
            type: "answer",
            from: myName.value.trim(),
            to: data.from,
            payload: answer,
          })
        );
      } else if (data.type === "candidate") {
        if (pc && data.payload) {
          await pc.addIceCandidate(new RTCIceCandidate(data.payload));
        }
      }
    };
  } catch (error) {
    ElMessage.error(`c: ${error.message}`);
    console.log("摄像头启动失败", error);
  }
};

// 屏幕共享处理
const startScreenShare = async () => {
  try {
    screenStream.value = await navigator.mediaDevices.getDisplayMedia({
      video: {
        cursor: "always",
        displaySurface: "monitor",
        width: { ideal: 1280 },
        height: { ideal: 720 },
      },
      audio: false,
    });

    screenRef.value.srcObject = screenStream.value;
    // await initPeerConnection("screen");
    ElMessage.success("屏幕共享已启动");

    // 监听共享结束
    screenStream.value.getVideoTracks()[0].onended = () => {
      // stopScreenShare();
      ElMessage.warning("屏幕共享已结束");
    };
  } catch (error) {
    if (error.name !== "NotAllowedError") {
      ElMessage.error(`屏幕共享失败: ${error.message}`);
    }
  }
};

const createPeerConnection = async (remoteName) => {
  if (pc) return;

  pc = new RTCPeerConnection();

  if (!localStream) {
    console.error("localStream 不存在，无法添加 track");
    return;
  }

  localStream.getTracks().forEach((track) => {
    pc.addTrack(track, localStream);
  });

  pc.onicecandidate = (event) => {
    if (event.candidate) {
      ws.send(
        JSON.stringify({
          type: "candidate",
          from: myName.value.trim(),
          to: remoteName,
          payload: event.candidate,
        })
      );
    }
  };
};

onMounted(() => {
  if (props.showCamera) startCamera();
  if (props.showScreen) startScreenShare();
});
onUnmounted(() => {
  if (ws) {
    ws.close();
    ws = null;
  }
  if (pc) {
    pc.close();
    pc = null;
  }
  if (localStream) {
    localStream.getTracks().forEach((track) => track.stop());
    localStream = null;
  }
});

onUnmounted(() => {
  // stopMedia("camera");
  // stopMedia("screen");
});
</script>

<style scoped>
.video-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}
.video-box {
  position: relative;
  border: 1px solid #eee;
  border-radius: 4px;
}
.video-element {
  width: 100%;
  max-height: 300px;
  background: #000;
  border-radius: 4px;
}
</style>
